<template>
  <div>
    <van-nav-bar
      title="个人资料"
      right-text="保存"
      left-arrow
      @click-left="onBack"
      @click-right="onSave"
    />

    <div class="dll-edit" v-for="item in userList" :key="item">
      <div class="dll-edit-img">
        <img
          :src="item.img"
          style="
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto;
            margin-top: 120px;
          "
          @click="showPopup"
          alt=""
        />
      </div>
      <div
        style="
          text-align: center;
          margin-top: 65px;
          font-size: 15px;
          color: gray;
        "
      >
        <p>点击修改头像</p>
      </div>
      <div class="dll-edit-name">
        <span style="font-size: 20px; color: gray">昵称</span>
        <input type="text" v-model="item.name" />
      </div>
      <div class="dll-edit-sifnature">
        <span style="font-size: 20px; color: gray">简介</span>
        <div><input type="text" v-model="item.desc" /></div>
      </div>
      <div class="phote" v-show="phote">
        <video id="videoCamera" :width="videoWidth" :height="videoHeight" />
        <canvas
          style="display: none"
          id="canvasCamera"
          :width="videoWidth"
          :height="videoHeight"
        />
        <el-button @click="setImage()">拍照</el-button>
        <el-button @click="stopNavigator()">关闭摄像头</el-button>
      </div>
    </div>

    <van-popup v-model:show="show" round :style="{ padding: '64px' }">
      <van-button type="default" @click="getCompetence()" v-if="(phote = true)"
        >打开摄像头</van-button
      >

      <van-button type="default">
        <el-upload
          class="avatar-uploader"
          action="http://8.130.46.189:3000/dll/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <el-icon
            class="avatar-uploader-icon"
            style="width: 2em; font-style: normal"
            >相册</el-icon
          >
        </el-upload>
      </van-button>
    </van-popup>
  </div>
</template>

<script setup>
import { inject, ref, onMounted } from "vue";
import { Popup, showConfirmDialog } from "vant";
import { useRoute, useRouter } from "vue-router";
import axios from "axios";
// import Webcam from "webcamjs";

const route = useRoute();
const router = useRouter();

//获取用户信息
const userList = ref([]);
const userget = async () => {
  let { data } = await axios.get(
    "http://8.130.46.189:3000/dll/userList?id=" + route.query.id
  );
  console.log(data);
  userList.value = data;
};

// 相机拍照
const videoWidth = ref(380);
const videoHeight = ref(300);
const imgSrc = ref("");
const blobFile = ref(null);
const thisCancas = ref(null);
const thisContext = ref(null);
const thisVideo = ref(null);
const emit = defineEmits(["refreshDataList"]);

//   vue中使用摄像头拍照(监听摄像头)
function getCompetence() {
  show.value = false;
  thisCancas.value = document.getElementById("canvasCamera");

  thisContext.value = thisCancas.value.getContext("2d");

  thisVideo.value = document.getElementById("videoCamera");

  // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
  if (navigator.mediaDevices === undefined) {
    navigator.mediaDevices = {};
  }

  // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
  // 使用getUserMedia，因为它会覆盖现有的属性。
  // 这里，如果缺少getUserMedia属性，就添加它。
  if (navigator.mediaDevices.getUserMedia === undefined) {
    navigator.mediaDevices.getUserMedia = function (constraints) {
      // 首先获取现存的getUserMedia(如果存在)

      let getUserMedia =
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.getUserMedia;

      // 有些浏览器不支持，会返回错误信息
      // 保持接口一致
      if (!getUserMedia) {
        return Promise.reject(
          new Error("getUserMedia is not implemented in this browser")
        );
      }

      // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
      return new Promise(function (resolve, reject) {
        getUserMedia.call(navigator, constraints, resolve, reject);
      });
    };
  }

  let constraints = {
    audio: false,

    video: {
      width: videoWidth.value,

      height: videoHeight.value,

      transform: "scaleX(-1)",
    },
  };

  navigator.mediaDevices
    .getUserMedia(constraints)
    .then(function (stream) {
      // 旧的浏览器可能没有srcObject
      if ("srcObject" in thisVideo.value) {
        thisVideo.value.srcObject = stream;
      } else {
        // 避免在新的浏览器中使用它，因为它正在被弃用。
        thisVideo.value.src = window.URL.createObjectURL(stream);
      }

      thisVideo.value.onloadedmetadata = function (e) {
        thisVideo.value.play();
      };
    })

    .catch((err) => {
      console.log(err);
    });
}

//  绘制图片（拍照功能）
const setImage = async () => {
  // 点击，canvas画图
  thisContext.value.drawImage(
    thisVideo.value,
    0,
    0,
    videoWidth.value,

    videoHeight.value
  );

  // 获取图片base64链接
  let image = thisCancas.value.toDataURL("image/png");
  console.log(dataURLtoFile(image, "图片文件")); // 转换为file文件
  blobFile.value = dataURLtoFile(image, "图片文件");
  let formData = new FormData();
  formData.append("file", blobFile.value, "filename.jpg"); //图片内容
  //其中，blobFile 是包含图片内容的变量，"file" 是字段名，"filename.jpg" 是可选的文件名。
  // 将这个 FormData 对象发送到服务器，就可以上传图片数据了。
  // tips 此时已经获取到了fromData类型的数据
  console.log(formData.getAll("file")[0], "查看数据内容", formData); // 查看数据内容
  userList.value[0].img = image;
  localStorage.setItem("userList", JSON.stringify(userList.value));
  emit("refreshDataList", imgSrc.value);
  const adimg = await axios.post("http://8.130.46.189:3000/dll/photeImg", {
    img: userList.value[0].img,
    id: "6662a393b36a789fec4199d3",
  });
  stopNavigator();
  showPhote();
};

// base64转文件
function dataURLtoFile(dataurl, filename) {
  let arr = dataurl.split(",");
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

// 关闭摄像头
function stopNavigator() {
  thisVideo.value.srcObject.getTracks()[0].stop();
  showPhote();
}

//弹出框
const show = ref(false);
const showPopup = () => {
  show.value = true;
};
const phote = ref(false);
const showPhote = () => {
  phote.value = false;
};

//修改用户信息
const onSave = async () => {
  showConfirmDialog({
    title: "您确定要修改吗？",
  })
    .then(async () => {
      // Place the existing onSave logic here
      let data = await axios.post("http://8.130.46.189:3000/dll/update", {
        ids: userList.value,
      });
      userList.value = data.data;
      router.push("/my");
    })
    .catch(() => {
      // Handle cancel logic here
    });
};

//上传图片
const handleAvatarSuccess = (response, uploadFile) => {
  userList.value[0].img = response.path;
  show.value = false;
};

onMounted(() => {
  userget();
});
const onBack = () => {
  history.back();
};
</script>

<style scoped>
.dll-edit {
  width: 90%;
  margin: 0 auto;
}

div input {
  width: 280px;
  text-align: right;
  border: none;
}

.dll-edit-img {
  display: flex;
  justify-content: center;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  height: 60px;

  /* border-bottom: 1px solid #ECECEC;/ */
}

.dll-edit-name {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
  justify-content: space-between;
  /* padding: 10px 0; */
  height: 90px;
  margin-top: 10px;
  border-bottom: 1px solid #ececec;
}

.dll-edit-sifnature {
  display: flex;
  justify-content: center;
  align-items: center;
  justify-content: space-between;
  height: 80px;
  font-size: 20px;
  border-bottom: 1px solid #ececec;
}

.van-uploader__upload {
  display: node;
}
</style>
